<!--  -->
<template>
  <div class="login">
    <el-divider><i class="el-icon-mobile-phone"></i></el-divider>
    <!-- 密码登录 -->
    <div v-if="!isCaptcha">
      <el-form
        :model="ruleForm"
        status-icon
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="手机号" prop="phone">
          <el-input
            v-model.number="ruleForm.phone"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item class="pass" label="密码" prop="pass">
          <el-input
            type="password"
            v-model="ruleForm.pass"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item class="passbtn">
          <el-button type="primary" @click="submitForm()">登录</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 验证码登录 -->
    <div v-else>
      <el-form
        :model="ruleForm"
        status-icon
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="手机号" prop="phone">
          <el-input
            v-model.number="ruleForm.phone"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <div class="getcap">
          <el-button v-show="!isSend" @click="getCaptcha" type="text"
            >点击获取验证码</el-button
          >
          <el-button
            v-show="isSend"
            @click="getCaptcha"
            :disabled="true"
            type="text"
            >验证码已发送{{ countdown + "s" }}</el-button
          >
        </div>
        <el-form-item label="验证码" prop="captcha">
          <el-input
            type="text"
            v-model="ruleForm.captcha"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item class="btn">
          <el-button type="primary" @click="submitForm()">登录</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="getcap">
      <div v-show="!isCaptcha">
        <el-button @click="handleCaptcha" type="text">短信登录</el-button>
        <el-checkbox v-model="checked">自动登录</el-checkbox>
      </div>
      <el-button v-show="isCaptcha" @click="handleCaptcha" type="text"
        >密码登录</el-button
      >
    </div>
  </div>
</template>

<script>
import axios from "axios";
import {
  getLogin,
  getUserPrivatePlayList,
  getCaptcha,
  getTokenLogin,
} from "util/login.js";
import { mapState, mapMutations, mapGetters } from "vuex";

export default {
  name: "",
  data() {
    //验证手机号
    var validatePhone = (rule, value, callback) => {
      var myreg = /^[1][3,4,5,7,8,9][0-9]{9}$/;

      if (value === "") {
        return callback(new Error("手机号不能为空"));
      } else if (!myreg.test(value)) {
        return callback(new Error("请输入正确的手机号！"));
      } else {
        callback();
      }
    };
    //验证密码
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        callback();
      }
    };
    //验证验证码
    var validateCaptcha = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入验证码"));
      } else {
        callback();
      }
    };
    return {
      ruleForm: {
        //手机号
        phone: "",
        //密码
        pass: "",
        //验证码
        captcha: "",
        isShowLogin: true,
      },
      isCaptcha: false,
      //是否发送验证码
      isSend: false,
      //倒计时
      countdown: "60",
      timer: null,
      //是否选中自动登录
      checked: true,

      rules: {
        phone: [{ validator: validatePhone, trigger: "blur" }],
        pass: [{ validator: validatePass, trigger: "blur" }],
        captcha: [{ validator: validateCaptcha, trigger: "blur" }],
      },
    };
  },

  methods: {
    //设置cookie
    setCookie(c_name, c_pwd, exdays) {
      var exdate = new Date(); //获取时间
      exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exdays); //保存的天数
      //字符串拼接cookie
      window.document.cookie =
        "userName" + "=" + c_name + ";path=/;expires=" + exdate.toGMTString();
      window.document.cookie =
        "password" + "=" + c_pwd + ";path=/;expires=" + exdate.toGMTString();
    },
    //清除cookie
    clearCookie: function () {
      this.setCookie("", "", -1); //修改2值都为空，天数为负1天就好了
    },
    //点击登录
    async submitForm() {
      if (this.isCaptcha) {
        let { data } = await getLogin(
          this.ruleForm.phone,
          this.ruleForm.pass,
          this.ruleForm.captcha
        );
        // console.log(data)
        this.ruleForm.captcha = "";
        if (data.code !== 200)
          return this.$message.error("登陆失败,请检查登录信息!");
        this.$message.success("登陆成功");
        this.setCookie(this.ruleForm.phone, this.ruleForm.pass, 7);
        //保存用户信息
        this.$store.dispatch("userInfo/saveUserInfo", data.profile);
        sessionStorage.setItem("userinfo", JSON.stringify(data.profile));
        //保存用户登录状态
        this.$store.dispatch("userInfo/saveLoginStatus", "true");
        sessionStorage.setItem("loginStatus", "true");
        //获取用户私人歌单
        let {
          data: { playlist },
        } = await getUserPrivatePlayList(data.profile.userId);
        // console.log(playlist);
        //保存用户歌单信息
        this.$store.dispatch("userInfo/savePrivatePlayList", playlist);
        sessionStorage.setItem("userPrivatePlayList", JSON.stringify(playlist));
        //保存用户id
        this.$store.dispatch("userInfo/saveUserId", data.profile.userId);
        sessionStorage.setItem("userId", data.profile.userId);
        //传值给父组件
        this.$emit("func", this.isShowLogin);
        //获取cookie
        sessionStorage.setItem("token", data.token);
        sessionStorage.setItem("cookie", data.cookie);
      } else {
        let { data } = await getLogin(this.ruleForm.phone, this.ruleForm.pass);
        if (data.code !== 200)
          return this.$message.error("登陆失败,请检查登录信息!");
        this.$message.success("登陆成功");
        //保存用户信息
        this.$store.dispatch("userInfo/saveUserInfo", data.profile);
        sessionStorage.setItem("userinfo", JSON.stringify(data.profile));
        //保存用户登录状态
        this.$store.dispatch("userInfo/saveLoginStatus", "true");
        sessionStorage.setItem("loginStatus", "true");
        //获取用户私人歌单
        let {
          data: { playlist },
        } = await getUserPrivatePlayList(data.profile.userId);
        // console.log(playlist);
        //保存用户歌单信息
        this.$store.dispatch("userInfo/savePrivatePlayList", playlist);
        sessionStorage.setItem("userPrivatePlayList", JSON.stringify(playlist));
        //保存用户id
        this.$store.dispatch("userInfo/saveUserId", data.profile.userId);
        sessionStorage.setItem("userId", data.profile.userId);
        //传值给父组件
        this.$emit("func", this.isShowLogin);
        //获取cookie
        sessionStorage.setItem("token", data.token);
        sessionStorage.setItem("cookie", data.cookie);
        //判断复选框是否被勾选 勾选则调用配置cookie方法
        if (this.checked == true) {
          //传入账号名，密码，和保存天数3个参数
          this.setCookie(this.ruleForm.phone, this.ruleForm.pass, 5);
        } else {
          // console.log("清空Cookie");
          //清空Cookie
          this.clearCookie();
        }
      }
    },
    //重置
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    handleCaptcha() {
      this.isCaptcha = !this.isCaptcha;
    },
    loading() {
      this.countdown--;
      if (this.countdown == 0) {
        this.isSend = false;
      }
    },
    clearTimer() {
      clearInterval(this.timer);
      this.timer = null;
    },
    //获取验证码
    async getCaptcha() {
      var myreg = /^[1][3,4,5,7,8,9][0-9]{9}$/;
      if (myreg.test(this.ruleForm.phone)) {
        await getCaptcha(this.ruleForm.phone);
        this.isSend = true;
        let that = this;
        that.loading();
        that.timer = setInterval(() => {
          if (that.countdown === 0) {
            that.clearTimer();
          } else {
            that.loading();
          }
        }, 1000);
      } else {
        this.$message("请输入手机号");
      }
    },
    //设置cookie
    setCookie(c_name, c_pwd, exdays) {
      var exdate = new Date(); //获取时间
      exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exdays); //保存的天数
      //字符串拼接cookie
      window.document.cookie =
        "userName" + "=" + c_name + ";path=/;expires=" + exdate.toGMTString();
      window.document.cookie =
        "userPwd" + "=" + c_pwd + ";path=/;expires=" + exdate.toGMTString();
    },
  },
};
</script>

<style scoped>
.login {
  padding-top: 80px;
  width: 350px;
  height: 300px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.3);
}
.el-input {
  width: 200px;
}
.el-divider {
  margin-bottom: 50px;
}
.el-icon-mobile-phone {
  color: red;
  font-size: 27px;
}
.el-form-item {
  margin-bottom: 0;
}
.getcap {
  margin-top: 5px;
  text-align: center;
}
.getcap div {
  display: flex;
  align-items: center;
  justify-content: space-evenly;
}
.passbtn {
  margin-top: 20px;
}
.btn {
  margin-top: 20px;
}
.pass {
  margin-top: 20px;
}
</style>